package cn.szzsi.file;

import cn.szzsi.core.CoreConfig;
import cn.szzsi.core.file.FileMsg;
import cn.szzsi.core.file.Files;
import cn.szzsi.core.file.FilesService;
import cn.szzsi.core.file.QiniuUtil;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.core.Controller;
import com.jfinal.core.JFinal;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.upload.UploadFile;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.time.DateFormatUtils;

import java.io.File;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 *文件上传
 */
public class UploadFileController extends Controller {
    //上传图片(原图)
    public void uploadpicture(){
        UploadFile uploadFile=getFile("imgFile");
        String img= PropKit.get("file.url")+uploadFile.getFileName();
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("error",0);
        map.put("url",img);
        renderJson(map);

    }

    public void index(){
        render("/file.html");
    }

    public void getVideoFile(){
        String shopId=getPara("shopId","0");
        String type=getPara("type","d");
        UploadFile uploadFile=getFile("videoFile");
        File resFile = new File(JFinal.me().getServletContext().getRealPath("upload")+"/"+uploadFile.getFileName());//默认文件路径
        String suffix= resFile.toString().substring(resFile.toString().lastIndexOf("."));//后缀(图片格式)
        String fileName=getFileName(shopId,suffix);
        Boolean backBoolean= QiniuUtil.qu.upload(resFile.toString(),fileName);//文件传到七牛云

        Map<String,Object> map=new HashMap<String,Object>();
        if(backBoolean){
            String prefix=fileName.substring(fileName.indexOf("/")+1,fileName.lastIndexOf("/"));//前缀(201703格式)
            String originalNamer=resFile.toString().substring(resFile.toString().lastIndexOf(File.separator)+1);//原文件名
            String pid="";
            //查看该店铺是否存在该文件夹
            Files files = Files.dao.getByShopIdAndTypeAndUrl(shopId,0,prefix);
            if(files ==null){
                FilesService.service.saveFiles(shopId,"0",prefix,0,0,"",0L);
            }
            pid = Files.dao.getByShopIdAndTypeAndUrl(shopId,0,prefix).getStr("id");//父级ID
            FilesService.service.saveFiles(shopId,pid, CoreConfig.p.get("qiniu.url")+fileName,1,0,originalNamer,resFile.length());
        }
        resFile.delete();//上传成功后将本地服务器文件删除
        if("k".equals(type)){//kindEditor
            map.put("error",0);
            map.put("url", CoreConfig.p.get("qiniu.url")+fileName);
        }else if("d".equals(type)){//自己封装单独上传
            map.put("message", new FileMsg());
            map.put("url", CoreConfig.p.get("qiniu.url")+fileName);
        }
        renderHtml(JsonKit.toJson(map));
    }

    //上传图片(积分商城)
    public void integraluploadpicture(){
        UploadFile uploadFile=getFile("imgFile");
        File resFile = new File(JFinal.me().getServletContext().getRealPath("upload")+"/"+uploadFile.getFileName());
        String newFileName= System.currentTimeMillis()+resFile.toString().substring(resFile.toString().lastIndexOf("."));
        File newFile = new File(JFinal.me().getServletContext().getRealPath("upload")+"/"+newFileName);
        resFile.renameTo(newFile);
        String img= PropKit.get("web.url")+ PropKit.get("file.url")+newFileName;
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("error",0);
        map.put("url",img);
        renderJson(map);

    }


    /**
     * app多图或者单图上传
     */
    public void appuploadpicture(){
        getResponse().setHeader("Access-Control-Allow-Origin", "*");
        getResponse().setHeader("Access-Control-Allow-Methods", "GET,POST");
        String shopId="app";
        List<UploadFile> uploadFiles=getFiles();
        System.out.println("size----"+uploadFiles.size());
        List list=new ArrayList();
        JSONObject jsonObject=new JSONObject();
        for(UploadFile uploadFile:uploadFiles){
            File resFile = new File(JFinal.me().getServletContext().getRealPath("upload")+"/"+uploadFile.getFileName());//默认文件路径
            String suffix= resFile.toString().substring(resFile.toString().lastIndexOf("."));//后缀(图片格式)
            String fileName=getFileName(shopId,suffix);
            Boolean backBoolean= QiniuUtil.qu.upload(resFile.toString(),fileName);//文件传到七牛云

            if(backBoolean){
                String prefix=fileName.substring(fileName.indexOf("/")+1,fileName.lastIndexOf("/"));//前缀(201703格式)
                String originalNamer=resFile.toString().substring(resFile.toString().lastIndexOf(File.separator)+1);//原文件名
                String pid="";
                //查看该店铺是否存在该文件夹
                Files files = Files.dao.getByShopIdAndTypeAndUrl(shopId,0,prefix);
                if(files ==null){
                    FilesService.service.saveFiles(shopId,"0",prefix,0,0,"",0L);
                }
                pid = Files.dao.getByShopIdAndTypeAndUrl(shopId,0,prefix).getStr("id");//父级ID
                FilesService.service.saveFiles(shopId,pid, CoreConfig.p.get("qiniu.url")+fileName,1,0,originalNamer,resFile.length());
            }
            resFile.delete();//上传成功后将本地服务器文件删除
            list.add(CoreConfig.p.get("qiniu.url")+fileName);

        }
        jsonObject.put("url",list);
        System.out.println(JsonKit.toJson(Ret.create("result",1).set("msg","获取成功").set("data",jsonObject)));
        renderHtml(JsonKit.toJson(Ret.create("result",1).set("msg","获取成功").set("data",jsonObject)));
    }


    //上传图片(new)
    public void uploadfile() {
        String shopId=getPara("shopId");
        String type=getPara("type");
        UploadFile uploadFile=getFile();
        File resFile = new File(JFinal.me().getServletContext().getRealPath("upload")+"/"+uploadFile.getFileName());//默认文件路径
        String suffix= resFile.toString().substring(resFile.toString().lastIndexOf("."));//后缀(图片格式)
        String fileName=getFileName(shopId,suffix);
        Boolean backBoolean= QiniuUtil.qu.upload(resFile.toString(),fileName);//文件传到七牛云

        Map<String,Object> map=new HashMap<String,Object>();
        if(backBoolean){
            String prefix=fileName.substring(fileName.indexOf("/")+1,fileName.lastIndexOf("/"));//前缀(201703格式)
            String originalNamer=resFile.toString().substring(resFile.toString().lastIndexOf(File.separator)+1);//原文件名
            String pid="";
            //查看该店铺是否存在该文件夹
            Files files = Files.dao.getByShopIdAndTypeAndUrl(shopId,0,prefix);
            if(files ==null){
                FilesService.service.saveFiles(shopId,"0",prefix,0,0,"",0L);
            }
             pid = Files.dao.getByShopIdAndTypeAndUrl(shopId,0,prefix).getStr("id");//父级ID
             FilesService.service.saveFiles(shopId,pid, CoreConfig.p.get("qiniu.url")+fileName,1,0,originalNamer,resFile.length());
        }
        resFile.delete();//上传成功后将本地服务器文件删除
        if("k".equals(type)){//kindEditor
            map.put("error",0);
            map.put("url", CoreConfig.p.get("qiniu.url")+fileName);
        }else if("d".equals(type)){//自己封装单独上传
            map.put("message", new FileMsg());
            map.put("url", CoreConfig.p.get("qiniu.url")+fileName);
        }
        renderHtml(JsonKit.toJson(map));
    }

    /**
     *
     */
    public void newuploadfile() {
        String shopId=getPara("shopId");
        UploadFile uploadFile=getFile();
        String resFileName=uploadFile.getFileName();//原始文件名称
        File resFile = new File(JFinal.me().getServletContext().getRealPath("upload")+"/"+resFileName);//默认文件路径
        String suffix= resFile.toString().substring(resFile.toString().lastIndexOf("."));//后缀(图片格式)
        String fileName=getFileName(shopId,suffix);
        Boolean backBoolean= QiniuUtil.qu.upload(resFile.toString(),fileName);//文件传到七牛云

        Map<String,Object> map=new HashMap<String,Object>();
        if(backBoolean){
            String prefix=fileName.substring(fileName.indexOf("/")+1,fileName.lastIndexOf("/"));//前缀(201703格式)
            String originalNamer=resFile.toString().substring(resFile.toString().lastIndexOf(File.separator)+1);//原文件名
            String pid="";
            //查看该店铺是否存在该文件夹
            Files files = Files.dao.getByShopIdAndTypeAndUrl(shopId,0,prefix);
            if(files ==null){
                FilesService.service.saveFiles(shopId,"0",prefix,0,0,"",0L);
            }
            pid = Files.dao.getByShopIdAndTypeAndUrl(shopId,0,prefix).getStr("id");//父级ID
            FilesService.service.saveFiles(shopId,pid, CoreConfig.p.get("qiniu.url")+fileName,1,0,originalNamer,resFile.length());
        }
        resFile.delete();//上传成功后将本地服务器文件删除
        map.put("code",0);
        map.put("resFileName",resFileName);
        map.put("url", CoreConfig.p.get("qiniu.url")+fileName);
        renderJson(JsonKit.toJson(map));
    }


    /**
     * kindEditor图片空间
     */
    public void fileManagerJson(){
        String shopId=getPara("shopId");//店铺ID
        String path=getPara("path");//路径
        String order=getPara("order","NAME");
        String orderBy="";//排序类型
        if("SIZE".equals(order)){
            orderBy="size";
        }else if ("NAME".equals(order)){
            orderBy="originalName";
        }else{
            orderBy="type";
        }
        List<Object> list=new ArrayList<Object>();
        Map<String,Object>listMap=new HashMap<String,Object>();
        if(path.contains("/")){//文件
            Files pFiles= Files.dao.getByShopIdAndTypeAndUrl(shopId,0,path.substring(0,path.lastIndexOf("/")));
            String pid=pFiles.getStr("id");
            List<Files> filesList= Files.dao.getByPid(pid,orderBy);
            for(Files files:filesList){
                Map<String,Object>map=new HashedMap();
                map.put("is_dir",false);
                map.put("has_file", false);
                map.put("filesize", files.getInt("size"));
                map.put("is_photo",true);
                map.put("filetype",files.getStr("url").substring(files.getStr("url").lastIndexOf(".") + 1).toLowerCase());
                map.put("filename",files.getStr("url"));
                map.put("datetime",files.getDate("createDate"));
                list.add(map);
            }
            listMap.put("file_list",list);
            listMap.put("total_count",filesList.size());
        }else{//文件夹
            List<Files>filesList;
            filesList= Files.dao.getByShopIdAndType(shopId,0,orderBy);
            for(Files files:filesList){
                Map<String,Object>map=new HashedMap();
                map.put("is_dir",true);
                map.put("has_file", true);
                map.put("filesize", 0L);
                map.put("is_photo",false);
                map.put("filetype","");
                map.put("filename",files.getStr("url"));
                map.put("datetime",files.getDate("createDate"));
                list.add(map);
            }
            listMap.put("file_list",list);
            listMap.put("total_count",filesList.size());
        }
            listMap.put("current_dir_path",path);
            listMap.put("current_url","");
            listMap.put("moveup_dir_path","");

        renderJson(listMap);
    }

    /**
     * 自己封装的(图片空间)
     */
    public void browser(){
        String shopId=getPara("shopId");//店铺ID
        String path=getPara("path");//路径
        String order=getPara("orderType","time");
        String orderBy="";//排序类型
        if("size".equals(order)){
            orderBy="size";
        }else if ("name".equals(order)){
            orderBy="originalName";
        }else{
            orderBy="time";
        }
        List<Object> list=new ArrayList<Object>();
        if(path.equals("/")){//文件夹
            List<Files>filesList= Files.dao.getByShopIdAndType(shopId,0,"originalName");
            for(Files files:filesList){
                Map<String,Object>map=new HashedMap();
                map.put("isDirectory",true);
                map.put("name",files.getStr("url"));
                try {
                    map.put("lastModified",strToTimestamp(files.getDate("createDate").toString()));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                map.put("url","");
                map.put("size","");
                list.add(map);
            }
        }else{//文件
            String pidUrl=path.substring(1,path.lastIndexOf("/"));
            Files pFiles= Files.dao.getByShopIdAndTypeAndUrl(shopId,0,pidUrl);
            String pid=pFiles.getStr("id");
            List<Files> filesList= Files.dao.getByPid(pid,orderBy);
            for(Files files:filesList){
                Map<String,Object>map=new HashedMap();
                map.put("isDirectory",false);
                map.put("name",files.getStr("originalName"));
                map.put("url",files.getStr("url"));
                try {
                    map.put("lastModified",strToTimestamp(files.getDate("createDate").toString()));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                map.put("size",files.getInt("size"));
                list.add(map);
            }

        }
        renderJson(list);

    }


    /**
     * 根据shopId获取图片名称
     * @param shopId
     */
    public String getFileName(String shopId,String suffix){
        return shopId+"/"+ DateFormatUtils.format(new Date(),"yyyyMM")+"/"+ StrKit.getRandomUUID()+suffix;
    }

    /**
     * 日期字符串转换成时间戳
     * @param dateStr
     * @return
     * @throws ParseException
     */
    public static Long strToTimestamp(String dateStr) throws ParseException {
        DateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date=df.parse(dateStr);
        long timestamp=date.getTime();
        return timestamp;
    }

}
